package com.giscloud.amp.controller;

import com.giscloud.commons.utils.JacksonUtil;
import com.giscloud.commons.utils.StringUtils;
import com.giscloud.redis.utils.RedisUtils;
import com.giscloud.token.cache.LocalCacheManager;
import com.giscloud.token.utils.RedisConstant;
import com.giscloud.token.utils.Token;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @Author:gxd
 * @Description:
 * @Date: 17:09 2018/3/7
 * @Modified By:
 */
@Controller
@Log4j2
public class BaseController {
    public final static String ACCESS_TOKEN = "giscloud-token";
    @Value("${spring.cache.type}")
    private String cacheType;
    @Resource
    private RedisUtils redisUtils;
    @Autowired
    private LocalCacheManager localCacheManager;
    /**
     * 获取getRequest
     * @return
     */
    public HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    public String  getAccessToken(){
        String accessToken = getRequest().getHeader(ACCESS_TOKEN);
        if(StringUtils.isBlank(accessToken)){
            accessToken = getRequest().getParameter(ACCESS_TOKEN);
        }
        return accessToken;
    }
    /**
     * 获取登录用户信息
     *
     * @return
     */
    public Token getToken(){
        if(StringUtils.isEmpty(getAccessToken())){
            return null;
        }
        String userJson = "";
        if("redis".equals(cacheType)) {
            if (redisUtils.get(RedisConstant.REDIS_USER_TOKEN + getAccessToken()) == null) {
                return null;
            }
            // 从Redis中获取用户信息
            userJson = (String) redisUtils.get(RedisConstant.REDIS_USER_TOKEN + getAccessToken());
        }else{
            if (localCacheManager.get(RedisConstant.REDIS_USER_TOKEN + getAccessToken()) == null) {
                return null;
            }
            // 从本地内存中获取用户信息
            userJson = localCacheManager.get(RedisConstant.REDIS_USER_TOKEN + getAccessToken());
        }
        return JacksonUtil.json2Bean(userJson, Token.class);
    }
}
